#!/bin/bash
# author tyb
# date 20240223

# 执行结果判断函数
function isgreen() {
    if [ $? -eq 0 ]; then
        echo -e "\e[32m$1==========>succeed\e[0m"
    else
        echo -e "\e[31m$1==========>failed\e[0m"
        # exit 1
    fi
}

# 网络测试函数
function network() {
    #超时时间
    local timeout=1

    #目标网站
    local target=www.baidu.com

    #获取响应状态码
    local ret_code
    ret_code=$(curl -I -s --connect-timeout ${timeout} ${target} -w "%{http_code}" | tail -n1)

    if [ "$ret_code" = "200" ]; then
        #网络畅通
        echo -e "\e[32m网络畅通==========>succeed\e[0m"
        return 0
    else
        #网络不畅通
        echo -e "\e[31m网络不畅通，请检查网络==========>succeed\e[0m"
        exit 1
    fi

}

zabbix_server="10.231.64.9"

network
# 安装软件
echo "安装zabbix代理"
if ! [ -e /optzabbix-release/zabbix-release_6.0-4+ubuntu22.04_all.deb ]; then
    cd /opt/ && wget https://repo.zabbix.com/zabbix/6.0/ubuntu/pool/main/z/zabbix-release/zabbix-release_6.0-4+ubuntu22.04_all.deb >/dev/null 2>&1
    isgreen "下载zabbix源"

    dpkg -i /opt/zabbix-release_6.0-4+ubuntu22.04_all.deb >/dev/null 2>&1
    isgreen "安装zabbix源"

    apt-get update >/dev/null 2>&1
    isgreen "更新源"

    apt install zabbix-agent2 zabbix-agent2-plugin-* zabbix-sender >/dev/null 2>&1
    isgreen "安装zabbix-agent"
fi
isgreen "安装zabbix代理"

# 修改配置文件
echo "修改配置文件"
if ! [ -e /etc/zabbix/zabbix_agent2.conf.bak ]; then
    mv /etc/zabbix/zabbix_agent2.conf /etc/zabbix/zabbix_agent2.conf.bak
    isgreen "备份配置文件"
    cat  > /etc/zabbix/zabbix_agent2.conf <<-EOF
PidFile=/var/run/zabbix/zabbix_agent2.pid
LogFile=/var/log/zabbix/zabbix_agent2.log
LogFileSize=0
ServerActive=$zabbix_server
Server=$zabbix_server
HostnameItem=system.hostname
Include=/etc/zabbix/zabbix_agent2.d/*.conf
PluginSocket=/run/zabbix/agent.plugin.sock
ControlSocket=/run/zabbix/agent.sock
Include=./zabbix_agent2.d/plugins.d/*.conf
HostMetadata=hyperxnode
EOF
isgreen "重写配置文件"
fi
isgreen "修改配置文件"

# 重启服务
echo "重启服务"
systemctl restart zabbix-agent2 > /dev/null 2>&1
isgreen "重启服务"

# 安装放贷软件
echo "安装防呆软件"
apt-get install molly-guard >/dev/null 2>&1
isgreen "安装防呆软件"